package driver

import (
	"time"

	"task/ecode"
	"task/models"

	log "github.com/sirupsen/logrus"
)

// AddResource add resource.
func AddResource(resourceId int64, dagId int, name string) error {
	var err error
	resource := &models.Resource{
		ResourceId: resourceId,
		DagId:      dagId,
		Name:       name,
		Status:     models.ResourceStatusNormal,
		CreateTime: time.Now(),
		UpdateTime: time.Now(),
	}
	if _, err = Engine.Insert(resource); err != nil {
		log.Errorf("AddResource engine error(%v)", err)
		return ecode.EngineError
	}
	return nil
}

// GetResource get resource.
func GetResource(resourceId int64) (*models.Resource, error) {
	var (
		ok  bool
		err error
	)
	resource := new(models.Resource)
	if ok, err = Engine.Id(resourceId).Where("status != ?", models.ResourceStatusDelete).Get(resource); err != nil {
		log.Errorf("GetResource engine error(%v)", err)
		return nil, ecode.EngineError
	}
	if !ok {
		return nil, nil
	}
	return resource, nil
}

// UpdateResourceStats1 update resource stats1.
func UpdateResourceStats1(resourceId, result int64) error {
	var err error
	state := new(models.Resource)
	state.Stats1 = result
	if _, err = Engine.Where("resource_id = ?", resourceId).Cols("stats1").Update(state); err != nil {
		log.Errorf("UpdateResourceStats1 engine error(%v)", err)
		return ecode.EngineError
	}
	return nil
}

// UpdateResourceStats2 update resource stats2.
func UpdateResourceStats2(resourceId, result int64) error {
	var err error
	state := new(models.Resource)
	state.Stats2 = result
	if _, err = Engine.Where("resource_id = ?", resourceId).Cols("stats2").Update(state); err != nil {
		log.Errorf("UpdateResourceStats2 engine error(%v)", err)
		return ecode.EngineError
	}
	return nil
}

// UpdateResourceStats3 update resource stats3.
func UpdateResourceStats3(resourceId, result int64) error {
	var err error
	state := new(models.Resource)
	state.Stats3 = result
	if _, err = Engine.Where("resource_id = ?", resourceId).Cols("stats3").Update(state); err != nil {
		log.Errorf("UpdateResourceStats3 engine error(%v)", err)
		return ecode.EngineError
	}
	return nil
}

// UpdateResourceStats4 update resource stats4.
func UpdateResourceStats4(resourceId, result int64) error {
	var err error
	state := new(models.Resource)
	state.Stats4 = result
	if _, err = Engine.Where("resource_id = ?", resourceId).Cols("stats4").Update(state); err != nil {
		log.Errorf("UpdateResourceStats4 engine error(%v)", err)
		return ecode.EngineError
	}
	return nil
}

// UpdateResourceResult update resource result.
func UpdateResourceResult(resourceId, result int64) error {
	var err error
	state := new(models.Resource)
	state.Result = result
	if _, err = Engine.Where("resource_id = ?", resourceId).Cols("result").Update(state); err != nil {
		log.Errorf("UpdateResourceStatsResult engine error(%v)", err)
		return ecode.EngineError
	}
	return nil
}
